/**
 * 高值耗材采购模块，提供医疗服务编辑页面初始化组件功能
 * 
 * @Date: 2016-1-25
 * @author: Jackson wang
 * @version: 1.0
 * @since: 1.0
 */

define(	["jquery", "sysmanMain", "msgServ", "flowInit", "datagridServ",
				"panelUtil", "deptUserSelect", "buttonEvent", "uploadfiles"],
		function($, sysmanMain, msgServ, flowInit, datagridServ, panelUtil,
				deptUserSelect, buttonEvent, uploadfiles) {

			'use strict';
			var _typeUrl = '/dictionary/getTree.action',
				_rootpath,
				el_width = 285, 
		     	el_big_width = 640, 
				window_width = 900, 
				window_height = 700, 
				rootid = 'panel-oa-highvalue', 
				
				//业务编码
				_bizcode = 'oaHighvalue',
				window_id = 'oa-highvalue-win', 
				edit_window_id='oa-highvalue-win',
				editIndex

			var public_method = {

				/**
				 * 初始化新增页面
				 * 
				 * @param _options.record
				 *            列表选中行
				 * @param _options.form
				 *            页面form对象
				 * @param _options.rootid
				 *            页面根节点id
				 * @param _options.flowStateSelector
				 *            流程状态字段选择器
				 */
				initEdit : function(_options) {
					
					
					if (window.console) {
						console.info(' recipel init loaded and startting ...')
					}

					private_method.initFileList();

					var queryUrl = '/' + sysmanMain.getRootPath()
							+ '/oaHighvalueSub/getListDomain.action';

					var gridParam = {

						height : 100,
						onClickCell : private_method.editCell,
						columns : [[{
									field : 'ck',
									checkbox : "true"
								}, {
									field : 'supply_name',
									title : '耗材名称',
									align : 'center',
									halign : 'center',
									width : 30,
									editor : 'text'
								}, {
									field : 'specification_model',
									title : '规格型号',
									width : 30,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'measurement_units',
									title : '计量单位',
									width : 30,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'purchase_num',
									title : '采购数量',
									width : 30,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'purchase_price',
									title : '进货价格',
									width : 30,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'serial_number',
									title : '流水号',
									width : 30,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}, {
									field : 'supplier_name',
									title : '供应商',
									width : 100,
									align : 'center',
									halign : 'center',
									editor : 'text'
								}]],
						rownumbers : true,
						animate : true,
						striped : true,
						border : true,
						idField : 'id',
						fitColumns : true,
						toolbar : '#' + window_id + ' #inner-table-highvalue'
					};
					if (_options && _options.record && _options.record.id) {
						gridParam.queryParams = {
							mainId : _options.record.id
						};
						gridParam.url = queryUrl;
					}

					var _el = $('#' + window_id + ' #dg-inner-highvalue')
					if (_el.length == 1) {
						_el.datagrid(gridParam)
					}
				},
				closeWindow : function() {
					$('#' + rootid + ' a.inner-table-btn').unbind('click');
					$('#' + window_id).empty()
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					_moduleConfig.initParam = {
						editable : true
					};
					sysmanMain.setCurrentModuConfig(_moduleConfig);
				},
				/**
				 * @param _options.rootid
				 * @param _options.conditionSelector
				 * @param _options.
				 */
				initList : function(_options) {
					private_method.initCondition(_options)
				},
				/**

				 * @param _options.record
				 */
				
				listbuttonExtends : function() {
					return {
						'评分':private_method.setEvalue
					}
				},
				buttonExtends : function() {
					var highvalue_inner_table = $('#' + window_id
							+ ' #dg-inner-highvalue')
					return {
						
						
						
						'耗材清单' : private_method.detailInfo,
						'附件' : function() {
							private_method.uploadInit()
						},
						'返回' : function() {
							console.info("I've got the return button!!!")
							private_method.changePanel({
										classType : 'edit-panel'
									})
							private_method.initFileList();
						},
						'上传' : function() {
							console.info("I've got the upload button!!!")
							private_method.upload()
						},
						'删除' : function() {
							console.info("I've got the upload button!!!")
							private_method.delFile()
						},
						'流程图' : function() {
							private_method.changePanel({
										classType : 'historicalDiagram-panel'
									})
						},
						'流程节点' : function() {
							private_method.changePanel({
										classType : 'historical-panel'
									})
							//flowInit.initList(_options)
						},
						'耗材添加' : function() {
							$(highvalue_inner_table).datagrid('appendRow', {})
						},
						'耗材删除' : function() {
							var record = $(highvalue_inner_table)
									.datagrid('getSelected');
							if (record) {
								var rowindex = $(highvalue_inner_table)
										.datagrid('getRowIndex', record);

								$(highvalue_inner_table).datagrid('deleteRow',
										rowindex);
							} else {
								msgServ.Msgslide('请选择删除的记录');
							}
						}
					}
				},

				reCreateField : function(_options) {
					private_method.reCreateField(_options)
				},
				rowDblClick : function(index, row) {
					private_method.rowDblClick(index, row)
				},

				beforeSubmit : function() {
					var _param = {
						window_id : window_id,
						table_id : 'dg-inner-highvalue',
						index : editIndex,
						field : 'supply_sub_info'
					}

					return buttonEvent.subListbeforeSubmit(_param);

				}

			}

			var private_method = {
					setEvalue:function(){
					var _param = {
						grid:$('#'+rootid +" table.dg-list"),
						window:$('#'+'Evalue' ),
						href:'/'+sysmanMain.getRootPath()+'/oaHighvalue/query/getPage.action?code=extendDlg',
						width:350,
						height:160,
						flag:true,
						onClose:function(){$('#'+'Evalue' ).empty()},
						existCheckElement:'form'}			
					    datagridServ.windowEdit(_param);		
				},
				
				
					editCell : function(index, field, value) {
					if (window.console)
						console.info(' editCell fired ...')
					var highvalue_inner_table = $('#' + window_id
							+ ' #dg-inner-highvalue')
					if (editIndex > -1 && (editIndex != index)) {
						$(highvalue_inner_table).datagrid('acceptChanges');
						$(highvalue_inner_table).datagrid('endEdit', editIndex);
					}

					$(highvalue_inner_table).datagrid('beginEdit', index);
					editIndex = index
				},
				initFileList : function() {
					var el = $('#' + edit_window_id
							+ ' form.main-form div.fileList')
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					var uploadListurl = '/upload/query/getInitListDomain.action'
					
					if (!_idEl.val()) {
						return;
					}
					var parm = {
						condition : {
							bizno : _idEl.val(),
							bizcode :_bizcode
						}
					}
					$.ajax({
								url : '/' + sysmanMain.getRootPath()
										+ uploadListurl,
								type : 'post',
								async : false,
								data : parm,
								success : function(result) {
									var _aParam = {
										target : el,
										data : result
									}

									private_method.appendList(_aParam)
								},
								failure : function(result) {
									if (window.console) {
										console.log('ajax call failured ...')
									}
								}
							})
				},
				appendList : function(_options) {
					if (_options.target && _options.data) {
						$(_options.target).empty();
						var _html = '点击名字下载';
						$.each(_options.data.rows, function(i, e) {
							console.info("got one");
							_html += '<span style = "cursor:pointer" onmouseover="font color="#0000FF"" onmouseout="font color="#FFFFFF"" class = "'
									+ 'fileDownBut'
									+ '"'
									+ 'fileId = "'
									+ e.id
									+ '">' + e.filename + '</span>';
						})
						// private_method.changeStyle()
						$(_options.target).append(_html)
						$(".fileDownBut").unbind('click')
						$(".fileDownBut").bind('click',
								private_method.fileDownload)

					}
				},
				changeStyle : function() {
					$(".fileDownBut").live({
								mouseover : function() {
									$(this).css("font-color", "blue");
								},
								mouseout : function() {
									$(this).css("font-color", "black");
								}
							})
				},

				fileDownload : function(e) {
					if (e) {
						var tpObj = e.currentTarget
						private_method.downloadfile($(tpObj).attr('fileId'));
					}
				},
				downloadfile : function(id) {
					if (window.console) {
						console.log('download file fired ')
					}
					var _url = '/' + sysmanMain.getRootPath()
							+ '/upload/downloadFileTest.action'
					var form = $("<form>");
					form.attr('style', 'display:none');
					form.attr('target', '');
					form.attr('method', 'post');
					form.attr('action', _url);
					var input1 = $("<input>");
					input1.attr('type', 'hidden')
					input1.attr('name', 'id')
					input1.attr('value', id);
					$('body').append(form);
					$(form).append(input1);

					form.submit();
					form.remove();

				},
				uploadInit : function() {
					var _moduleConfig = sysmanMain.getCurrentModuConfig();

					var $edit_window = $('#' + edit_window_id);
					var isSaved = false, _id
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					if (_idEl.length == 1) {
						_id = $(_idEl).val()
						if (_id) {
							isSaved = true
						}
					}

					if (!isSaved) {
						msgServ.Msgslide('保存后才能上传附件');
						return
					}
					this.uploadInitList({
								_moduleConfig : _moduleConfig
							});
					private_method.changePanel({
								classType : 'upload-panel'
							})
					if (_moduleConfig.bizcode && _id) {
						this.uploadInitRel({
									_moduleConfig : _moduleConfig
								});
					}
				},

				upload : function() {
					uploadfiles.upload()
				},
				delFile : function() {
					uploadfiles.del({
								biztableid : edit_window_id
										+ ' div.table-archive',
								rootPath : '/' + sysmanMain.getRootPath()
							})
				},
				uploadInitList : function(_options) {
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					uploadfiles.initList({
						data : {
							bizno : _idEl.val(),
							bizcode : _bizcode
						},
						rootPath : '/' + sysmanMain.getRootPath(),
						biztableid : edit_window_id
								+ ' div.upload-panel div.table-archive',
						toolbarid : edit_window_id
								+ ' div.upload-panel div.archive-btn a.file_upload_btn'

					})
				},

				uploadInitRel : function(_options) {
					var _idEl = $('#' + edit_window_id + ' form.main-form #id')
					uploadfiles.init({
						data : {
							bizno : _idEl.val(),
							bizcode : _bizcode
						},
						queue_id : edit_window_id
								+ ' div.upload-panel form.upload-form #queue',
						file_id : edit_window_id
								+ ' div.upload-panel form.upload-form #file_upload',
						rootPath : '/' + sysmanMain.getRootPath(),
						rootid : edit_window_id

					})
				},

				changePanel : function(_options) {
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					var tep = $('#' + edit_window_id + ' div.toggle-panel')
					console.info("run, saw?")
					tep.panel('close')
					if (tep.length > 0) {
						tep.panel('close')
						console.info("here all closed")
					}

					// var hd =
					// if(_options && _options.length > 0 && _options.classType
					// && _options.classType.length > 0){
					tep = $('#' + edit_window_id + '  div.'
							+ _options.classType)
					tep.panel('open')
					console.info("here " + _options.classType + " closed")
					// }
				},
				rowDblClick : function(index, row) {

					var editWindow = 'oa-highvalue-win';
					var _param = {}
					var _moduleConfig = sysmanMain.getCurrentModuConfig();
					if (!_moduleConfig) {
						_moduleConfig = {}
					}

					var flow_state_el = $('#' + rootid
							+ ' form.condition-form #flow_state')
					var flow_state_value = $(flow_state_el)
							.combobox('getValue')
					if (flow_state_value && flow_state_value === 'finished') {
						_param.editable = false
					} else {
						_param.editable = true
					}
					_moduleConfig.initParam = _param
					sysmanMain.setCurrentModuConfig(_moduleConfig)

					var $grid = $('#' + rootid + " table.dg-list");
					var $edit_window = $('#' + editWindow);
					var _url = '/' + sysmanMain.getRootPath()
							+ '/oaHighvalue/query/editPage.action';
					var _dgparam = {
						grid : $grid,
						window : $edit_window,
						href : _url,
						width : window_width,
						height : window_height,
						flag : true,
						existCheckElement : 'form'
					}

					_dgparam.onClose = public_method.closeWindow

					datagridServ.windowEdit(_dgparam);
				},
				/**
				 * 初始化条件查询框
				 * 
				 * @param _options.rootid
				 *            窗口根节点id
				 * @param _options.conditionSelector
				 *            条件框节点选择器
				 */
				initCondition : function(_options) {
					if (window.console) {
						console.info('recipel init loaded and starting...')
					}

					flowInit.initList(_options)
				},
				detailInfo : function() {
					if (window.console) {
						console.info('show detail loaded...')
					}

					var _config = {}
					// 查找耗材清单panel
					var innerpanelElement = $('#' + rootid
							+ ' div.inner-table-panel')

					var _inpatientno
					if (innerpanelElement.length > 0) {
						// 判断panel状态
						var isopen = panelUtil.getPanelState({
									target : innerpanelElement
								})
						if (isopen) {
							$(innerpanelElement).panel('close')
						} else {
							$(innerpanelElement).panel('open')
						}
					}

				},
				/**
				 * 更新质询子类信息
				 * 
				 * @param _options.form
				 * @param _options.record
				 * @param _options.target
				 */
				changeSubItem : function(_options) {
					var _subSelect = $(_options.form)
							.find('#inquiry_item_subcode')
					$(_subSelect).combobox({
						textField : 'name',
						valueField : 'id',
						readonly : false,
						url : _rootpath + '/dictionary/getTree.action?id='
								+ _options.record.id,
						onSelect : function(record) {
							var _item = $(_options.form)
									.find('#inquiry_item_sub')
							$(_item).val(record.text)
						}
					})
				},
				reCreateField : function(_options) {
					if (window.console) {
						console
								.info(' recipel reCreateField loaded and startting ...')
					}
					var data = _options.data
					var $form = _options.form
					_rootpath = '/' + sysmanMain.getRootPath()

					var normal_width_param = {
						width : el_width
					}
					var big_width_param = $.extend({}, {
								width : el_big_width,
								multiline : true,
								height : 50
							})
					var $form = _options.form
					// _rootpath = '/'+sysmanMain.getRootPath()

					// var normal_param = {required:true,editable:true}

					// var deptQueryUrl='/department/query/getTreeList.action'
					// var selectedRecord = $('#'+rootid + '
					// table.dg-list').datagrid('getSelected')
					// var fields = data.editFilter.enabled.split(',')
					var fConfig = {
						name : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),
						apply_date : $.extend({
									fieldType : 'datebox'
								}, normal_width_param),

						patient_id : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),
						surgery_date : $.extend({
									fieldType : 'datebox'
								}, normal_width_param),

						patient_name : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),
						patient_dept_name : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),

						outpatient_cost : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),
						supply_name : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),

						apply_deptname : $.extend({
									fieldType : 'textbox'
								}, normal_width_param),

						apply_content : $.extend({
									fieldType : 'textbox'
								}, big_width_param),

						dept_content : $.extend({
									fieldType : 'textbox'
								}, big_width_param),

						audit_content : $.extend({
									fieldType : 'textbox'
								}, big_width_param),

						chargeLeader_content : $.extend({
									fieldType : 'textbox'
								}, big_width_param),

						directLeader_content : $.extend({
									fieldType : 'textbox'
								}, big_width_param),

						fenguan_content : $.extend({
									fieldType : 'textbox'
								}, big_width_param),
						apply_name : $.extend({
									fieldType : 'textbox',
									onClickButton : function(data) {
										deptUserSelect.openPage({
													userids : window_id
															+ ' #apply_id',
													usernames : window_id
															+ ' #apply_name',
													deptid : window_id
															+ ' #apply_deptid',
													deptname : window_id
															+ ' #apply_deptname'
												})
									}
								}, normal_width_param)
					}
					flowInit.initField({
								fieldConfig : fConfig,
								fieldStatus : _options.data,
								window_id : window_id
							})

				     var param={
				     	window_id:window_id,
				     	user_id:'apply_id',
				     	user_name:'apply_name',
				     	user_deptid:'apply_deptid',
				     	user_deptname:'apply_deptname'
				     }
				     
				     deptUserSelect.initUser(param)
					$.messager.progress('close')
				}

			}

			return public_method;

		})